package com.winspread.app.AutoCompleteTextVeiw

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.Filter
import android.widget.Filterable
import android.widget.TextView
import com.winspread.active.extension.loge
import com.winspread.app.R

/**
 *Author: Amin
 *Data: 2023/1/3 14:37
 *
 *Description:
 *
 */
class AutoEdAdapter(var context: Context, var itemClick: (String) -> Unit) : BaseAdapter(), Filterable {


    var data: MutableList<String> = mutableListOf()


    fun setDataList(data: MutableList<String>) {
        this.data.clear()
        this.data.addAll(data)
        notifyDataSetChanged()
    }

    override fun getCount(): Int {
        return data.size
    }

    override fun getItem(position: Int): String {
        return data[position]
    }

    override fun getItemId(position: Int): Long {
        return position.toLong()
    }

    override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
        var viewHolder: ViewHolder
        var view: View

        if (convertView == null) {
            view = LayoutInflater.from(context).inflate(R.layout.item_auto_ed, null, false)
            viewHolder = ViewHolder(view)
            view.tag = viewHolder
        } else {
            view = convertView
            viewHolder = view.tag as ViewHolder
        }
        viewHolder.tv.text = data[position]

        viewHolder.tv.setOnClickListener {
            itemClick.invoke(data[position])
        }
        return view
    }


    inner class ViewHolder(view: View) {

        var tv = view.findViewById<TextView>(R.id.auto_tv)


    }


    override fun getFilter(): Filter {
        return MyFilter()

    }

    inner class MyFilter : Filter() {
        override fun performFiltering(constraint: CharSequence?): FilterResults {
            val results = FilterResults()
            val prefixString: String = constraint.toString()
            prefixString.loge()
            val mutableListOf = mutableListOf("jsjsj", "jsjsj1", "jsjsj12", "jsjsj123")
            results.values = mutableListOf
            results.count = mutableListOf.size
            return results

        }

        override fun publishResults(constraint: CharSequence?, results: FilterResults) {
            if (results.count > 0) {
                setDataList(results.values as MutableList<String>)
                notifyDataSetChanged()
            } else {
                notifyDataSetInvalidated()
            }
        }

    }


}